/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Filters;

import Transformers.Fourier;
import Types.Complex;
import Types.Convert;

/**
 * Filters certain frequencies out of the original signal.
 * @author Cliff
 */
public class FrequencyFilter {

    public static double[] filterFrequency(double[] source, int minFrequency,
            int maxFrequency) {
        Fourier fourier = new Fourier();
        if (maxFrequency >= source.length) {
            maxFrequency = source.length - 1;
        }
        Complex[] transformed = fourier.complexForward(Convert.fromDoubletoComplex(source));
        Complex[] newTransformed = new Complex[source.length];
        
        for (int i = 0; i < source.length; i++) {
            if (i <= maxFrequency && i >= minFrequency) {
                newTransformed[i] = transformed[i];
            }else{
                newTransformed[i] = new Complex(0,0);
            }
        }
        
        Complex[] filtered = fourier.complexReverse(newTransformed);
        
        double[] result = new double[filtered.length];
        for (int k = 0; k < filtered.length; k++) {
            double r = filtered[k].getRealPart();
            double i = filtered[k].getImagPart();
            result[k] = (r * r + i * i);
        }

        return result;
    }

    /**
     * 
     * @param source
     * @param minFrequency
     * @param maxFrequency
     * @return 
     */
    public static double[] filterFrequencyOld(double[] source, int minFrequency,
            int maxFrequency) {
        Fourier fourier = new Fourier();
        if (maxFrequency >= source.length) {
            maxFrequency = source.length - 1;
        }
        Complex[] transformed = fourier.complexForward(Convert.fromDoubletoComplex(source));
        Complex[] newTransformed = new Complex[maxFrequency - minFrequency + 1];
        int j = 0;
        for (int i = minFrequency; i < maxFrequency + 1; i++) {
            newTransformed[j] = transformed[i];
            j++;
        }
        Complex[] filtered = fourier.complexReverse(newTransformed);
        double[] result = new double[filtered.length];
        for (int k = 0; k < filtered.length; k++) {
            double r = filtered[k].getRealPart();
            double i = filtered[k].getImagPart();
            result[k] = (r * r + i * i);
        }

        return result;
    }
}
